package com.joesem.sale.client.widget.dialog

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Application
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatCheckBox
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.jiaxing.sale.client.R
import com.jiaxing.sale.client.databinding.DialogDeptUserBinding
import com.jiaxing.sale.client.databinding.LayoutToolbarBinding
import com.joesem.sale.client.base.*
import com.joesem.sale.client.network.data.DeptMode
import com.joesem.sale.client.network.data.DeptUserMode
import com.joesem.sale.client.utils.activityResult.launcherResult
import com.joesem.sale.client.utils.click

class DeptUserDialog : BaseActivity<DialogDeptUserBinding>() {

    private val viewModel by createViewModel<DeptUserViewMode>()

    private val multipleSelectedArr = arrayListOf<DeptUserMode>()

    private var adapter: BaseQuickAdapter<DeptUserMode, BaseViewHolder>? = null

    private var currentDeptId = ""

    override fun LayoutToolbarBinding.toolbar(savedInstanceState: Bundle?) {
        visible()
        toolbarTheme()
        toolbarTitle.text = intent.getStringExtra("title")
    }

    override fun DialogDeptUserBinding.initView(savedInstanceState: Bundle?) {
        viewModel.getDept()
        intent.getParcelableArrayListExtra<DeptUserMode>("multipleArr")?.apply {
            multipleSelectedArr.addAll(this)
        }
        val isMultipleSelected = intent.getBooleanExtra("isMultipleSelected", false)
        if (isMultipleSelected) llButtons.visible()
        else llButtons.gone()
        adapter =
            object : BaseQuickAdapter<DeptUserMode, BaseViewHolder>(R.layout.item_customer_user) {
                @SuppressLint("SetTextI18n")
                override fun convert(holder: BaseViewHolder, item: DeptUserMode) {
                    val vCheck = holder.getView<AppCompatCheckBox>(R.id.cbCheck)
                    if (isMultipleSelected) {
                        vCheck.visible()
                        val index = multipleSelectedArr.indexOfFirst { it.id == item.id }
                        vCheck.isChecked = index > -1
                    } else {
                        vCheck.gone()
                    }
                    holder.setText(R.id.tvCustomerName, item.realname.orEmpty())
                    holder.itemView.click {
                        if (!isMultipleSelected) {
                            setResult(Activity.RESULT_OK, Intent().apply {
                                putExtra("selected", item)
                            })
                            finish()
                        } else {
                            val index = multipleSelectedArr.indexOfFirst { it.id == item.id }
                            if (index > -1) {
                                multipleSelectedArr.removeAll { it.id == item.id }
                            } else {
                                multipleSelectedArr.add(item)
                            }
                            if (multipleSelectedArr.isEmpty()) {
                                tvCount.text = "请选择"
                            } else {
                                tvCount.text = "已选择${multipleSelectedArr.size}个"
                            }
                            notifyDataSetChanged()
                        }
                    }
                }
            }
        rvCustomerUserList.adapter = adapter
    }

    override fun DialogDeptUserBinding.initListener() {
        srlListRefresh.apply {
            setOnRefreshListener {
                viewModel.getDeptUser(currentDeptId, true)
            }
            setOnLoadMoreListener {
                viewModel.getDeptUser(currentDeptId, false)
            }
        }
        tabDept.addOnTabSelectedListener(object : OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                currentDeptId = tab?.tag.toString()
                adapter?.setList(arrayListOf())
                srlListRefresh.autoRefresh()
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {

            }

            override fun onTabReselected(tab: TabLayout.Tab?) {

            }

        })
        btnConfirm.click {
            if (multipleSelectedArr.isEmpty()) {
                toast("请选择至少一位~")
                return@click
            }
            setResult(Activity.RESULT_OK, Intent().apply {
                putParcelableArrayListExtra("multipleArrResult", multipleSelectedArr)
            })
            finish()
        }
    }

    override fun DialogDeptUserBinding.initIntent(intent: Any?) {
        when (intent) {
            is DeptUserViewMode.DeptIntent -> {
                tabDept.removeAllTabs()
                intent.data.forEach {
                    tabDept.addTab(tabDept.newTab().apply {
                        text = it.name
                        tag = it.id
                    })
                }
            }
            is DeptUserViewMode.DeptUserIntent -> {
                srlListRefresh.apply {
                    finishRefresh()
                    finishLoadMore()
                }
                if (intent.isFirst) {
                    adapter?.setList(intent.data)
                } else {
                    adapter?.addData(intent.data)
                }
            }
        }
    }
}


class DeptUserViewMode(application: Application) : BaseViewModel(application) {
    fun getDept() {
        request(isLoading = true, request = {
            getDept()
        }, response = {
            it.data?.let {
                actionIntent(DeptIntent(it.filterNotNull()))
            } ?: toast("部门数据为空~")
        }, responseFailed = {
            toast(it.message)
        })
    }

    fun getDeptUser(id: String?, isFirst: Boolean) {
        request(request = {
            getDeptUser(id, isFirst)
        }, response = {
            actionIntent(DeptUserIntent(it.data?.filterNotNull() ?: arrayListOf(), isFirst))
        }, responseFailed = {
            actionIntent(DeptUserIntent(arrayListOf(), isFirst))
            toast(it.message)
        })
    }

    class DeptIntent(val data: List<DeptMode>)
    class DeptUserIntent(val data: List<DeptUserMode>, val isFirst: Boolean)
}

fun optionDeptUser(
    activity: AppCompatActivity, title: String, responsibilitySelected: (DeptUserMode) -> Unit = {}
) {
    activity.launcherResult<DeptUserDialog>(
        "title" to title,
    ) { _: Int, data: Intent? ->
        data?.getParcelableExtra<DeptUserMode>("selected")?.let {
            responsibilitySelected.invoke(it)
        }
    }
}

fun optionMultipleDeptUser(
    activity: AppCompatActivity,
    title: String,
    multipleArr: List<DeptUserMode>,
    responsibilitySelected: (List<DeptUserMode>) -> Unit = {}
) {
    activity.launcherResult<DeptUserDialog>(
        "multipleArr" to multipleArr,
        "title" to title,
        "isMultipleSelected" to true
    ) { _: Int, data: Intent? ->
        data?.getParcelableArrayListExtra<DeptUserMode>("multipleArrResult")
            ?.let(responsibilitySelected)
    }
}